package com.cheng.shiro;

import com.cheng.common.exception.CommonException;
import com.cheng.common.utils.CodeUtil;
import com.cheng.common.utils.PswdUtil;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author: ChengJW
 * @date: 2021/11/2 7:24
 * @version: 1.0
 * @description: 自定义密码匹配器
 */
public class CustomCreditMatcher implements CredentialsMatcher {

    private final static Logger log = LoggerFactory.getLogger(CodeUtil.class);

    /**
    * @author: ChengJW
    * @params: [authenticationToken, authenticationInfo]
    * @return: boolean
    * @date: 2021/11/2
    * @description: authenticationToken 登录时生成; authenticationInfo 在 realm 中生成
    */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) {

        //强制转换token类型
        try {
            UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
            String passwordToken = String.valueOf(token.getPassword());
            String passwordInfo = String.valueOf(authenticationInfo.getCredentials());
            return PswdUtil.createPswd(CodeUtil.SALT,passwordToken).equals(passwordInfo);
        } catch (Exception exception) {
            log.error("CustomCreditMatcher-doCredentialsMatch");
            log.error(exception.getMessage(),exception);
            throw new CommonException(null,"CustomCreditMatcher","doCredentialsMatch",exception);
        }
    }
}
